import { http } from '@idmy/core'

export const getTemplate = id =>
  http.get(
    '/api/inv/print-template/getExcludeContent/' + id,
    {},
    {
      cache: {
        key: 'print-template-get-' + id,
        expire: 0,
      },
    }
  )

export const pagePrintTemplate = pageIn => http.post('/api/inv/print-template/page', pageIn)

export const createOrUpdate = params => {
  if (params.id) {
    return http.post('/api/inv/print-template/update', params)
  } else {
    return http.post('/api/inv/print-template/create', params)
  }
}

function createScript(content) {
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.text = content
  return script
}

export async function loadAllTemplates() {
  let templates = await http.post<any[]>(`/api/inv/print-template/all`, {})
  const head = document.head || document.getElementsByTagName('head')[0] || document.documentElement
  let js = ''
  templates.forEach(item => {
    const content = item.content.replace('export default ', '')
    js += `window.PRINT_TEMPLATE_${item.id}=${content};`
  })
  head.appendChild(createScript(js))
}
